package com.jacen.fzxs.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 微信签名工具
 * @author Jacen
 *
 */
@Component
public class SignUtil {

	/**
     * 与接口配置信息中的 token 一值
     */
    private static String token = "jacen_fzxs";
    
//  private static String appID = "wxd39cd0d8fef2e3c8";
    private static String appID = "wxf1a424a15cacb802";//墙体
    
    //b466d4b4f555e80c8a762af9bd0e0e19
//  private static String appSecret = "b466d4b4f555e80c8a762af9bd0e0e19";
    private static String appSecret = "e24f4f4fb17717762c1ebd4e85df547a";
    
    public static String accessToken = "";
    
    public static String openId = "or0XvjkNmEq9c2y8TghuyyyrXe1o";
    
    private static Logger logger = LoggerFactory.getLogger(SignUtil.class);
     
    /**
     * 验证签名
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    public static boolean checkSignature(String signature, String timestamp, String nonce){
        String[] arr = new String[]{token, timestamp, nonce};
        // 将 token, timestamp, nonce 三个参数进行字典排序
        Arrays.sort(arr);
        StringBuilder content = new StringBuilder();
        for(int i = 0; i < arr.length; i++){
            content.append(arr[i]);
        }
        MessageDigest md = null;
        String tmpStr = null;
         
        try {
            md = MessageDigest.getInstance("SHA-1");
            // 将三个参数字符串拼接成一个字符串进行 shal 加密
            byte[] digest = md.digest(content.toString().getBytes());
            tmpStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
        		logger.error(e.getMessage());
        }
        content = null;
        // 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
        System.out.println("tmpStr:"+tmpStr);
        return tmpStr != null ? tmpStr.equals(signature.toUpperCase()): false;
    }
     
    public static String getAccessToken() throws Exception{
    	String urlStr = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appID+"&secret="+appSecret;
    	String json = HttpUtil.sendRequest(HttpUtil.METHOD_GET, urlStr);
    	JSONObject jsonObject = JSON.parseObject(json);
		return (String) jsonObject.get("access_token");
    }
    
    public static JSONObject getUserInfo(String accessToken,String openId) throws Exception{
    	String urlStr = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+openId+"&lang=zh_CN";
    	String json = HttpUtil.sendRequest(HttpUtil.METHOD_GET, urlStr);
    	return JSON.parseObject(json);
    }
    
    public static String getInstanceAccessToken() throws Exception{
    	if(accessToken==null)
    		accessToken = getAccessToken();
    	return accessToken;
    }
    
    /**
     * 将字节数组转换为十六进制字符串
     * @param digest
     * @return String 十六进制字符串
     */
    private static String byteToStr(byte[] digest) {
        String strDigest = "";
        for(int i = 0; i < digest.length; i++){
            strDigest += byteToHexStr(digest[i]);
        }
        return strDigest;
    }
     
    /**
     * 将字节转换为十六进制字符串
     * @param b
     * @return String 十六进制字符串
     */
    private static String byteToHexStr(byte b) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(b >>> 4) & 0X0F];
        tempArr[1] = Digit[b & 0X0F];
         
        String s = new String(tempArr);
        return s;
    }
    
    public void task(){
    	int times = 0;
    	while(true){
    		try{
        		accessToken = getAccessToken();
        		break;
        	}catch(Exception e){
        		times++;
        		accessToken = null;
        	}
    		if(times==3)break;
    	}
    }
    
    
    public static void main(String[] args) throws Exception {
    	String accessToken = SignUtil.getAccessToken();
    	System.out.println(accessToken);
    	JSONObject jsonObject = SignUtil.getUserInfo(accessToken,"or0XvjkNmEq9c2y8TghuyyyrXe1o");
    	System.out.println(jsonObject.get("nickname"));
	}

}
